﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using System.Linq;
namespace eventr.Model
{
    public class ImageViewManager
    {

        public event EventHandler DataLoaded;

        List<ImageMetaData> metaData = null;
        WebClient wc;
        public ImageViewManager()
        {
            wc = new WebClient();
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);            
        }

        public void DownloadData(Uri imageDataFile)
        {            
            wc.DownloadStringAsync(imageDataFile);            
        }

        public List<ImageMetaData> MetaData
        {
            get
            {
                return metaData;
            }
        }

        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            List<ImageMetaData> list = new List<ImageMetaData>();

            string xml = e.Result;            

            XDocument doc = XDocument.Parse(xml);

            doc.Root.Elements("Image").ToList<XElement>().ForEach(
                         p =>
                         {
                             //note the id must be one less than the zorder from 
                             //the metadata file... 
                             int id = Convert.ToInt32(p.Attribute("id").Value);
                             string url = p.Attribute("url").Value;
                             string tag = p.Attribute("tag").Value;
                             string title = p.Attribute("title").Value;
                             string blurb = p.Value.Trim();
                             string video = "";
                             if (p.Attribute("video") != null)
                             {
                                 video = p.Attribute("video").Value;
                             }

                             //map this id back to the original collection
                             ImageMetaData item = new ImageMetaData(id, tag)
                             {
                                 Blurb = blurb,
                                 Title = title,
                                 Url = url,
                                 Video = video
                             };
                             list.Add(item);

                         }
                     );

            metaData = list;

            if (DataLoaded != null)
            {
                DataLoaded(this, EventArgs.Empty);
            }
        }       

    }
}
